package info.batcloud.fanli.core.service.impl;

import info.batcloud.fanli.core.entity.ChannelCommissionItem;
import info.batcloud.fanli.core.repository.ChannelCommissionItemRepository;
import info.batcloud.fanli.core.service.ChannelCommissionItemService;
import info.batcloud.fanli.core.service.CommissionItemService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ChannelCommissionItemServiceImpl implements ChannelCommissionItemService {

    @Inject
    private ChannelCommissionItemRepository channelCommissionItemRepository;

    @Inject
    private CommissionItemService commissionItemService;

    @Override
    public Map<Long, List<Long>> findChannelIdListByItemIdList(List<Long> itemIds) {

        List<ChannelCommissionItem> list = channelCommissionItemRepository.findByCommissionItemIdIn(itemIds);

        Map<Long, List<Long>> map = new HashMap<>();
        for (ChannelCommissionItem cci : list) {
            List<Long> channelIds = map.get(cci.getCommissionItemId());
            if (channelIds == null) {
                channelIds = new ArrayList<>();
                map.put(cci.getCommissionItemId(), channelIds);
            }
            channelIds.add(cci.getChannelId());
        }
        return map;
    }

    @Override
    public void addCommissionItemToChannel(long itemId, long channelId) {
        ChannelCommissionItem ci = channelCommissionItemRepository.findByCommissionItemIdAndChannelId(itemId, channelId);
        if (ci == null) {
            ci = new ChannelCommissionItem();
            ci.setChannelId(channelId);
            ci.setCommissionItemId(itemId);
            channelCommissionItemRepository.save(ci);
        }
    }

    @Override
    @Transactional
    public void deleteByChannelId(long channelId) {
        while (true) {
            List<ChannelCommissionItem> channelCommissionItems = this.channelCommissionItemRepository.findTop1000ByChannelId(channelId);
            List<Long> itemIds = channelCommissionItems.stream().map(cci -> cci.getCommissionItemId()).collect(Collectors.toList());
            channelCommissionItemRepository.delete(channelCommissionItems);
            commissionItemService.pushDocumentByItemIdList(itemIds);
            if (channelCommissionItems.size() < 1000) {
                break;
            }
        }
    }
}
